import React, { useState } from 'react';
import {
  Modal,
  Form,
  Row,
  Col,
  Button,
  Input,
  Select,
  Upload,
  DatePicker,
} from 'antd';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import { Editor } from 'react-draft-wysiwyg';
import { ContentState, convertToRaw, EditorState } from 'draft-js';
import { UploadOutlined } from '@ant-design/icons';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import request from '@/http';
import qs from 'qs';
import moment from 'moment';

interface UserEditObject {
  isModalVisible: boolean;
  key?: number;
  title?: string;
  completeDate?: string;
  appendsLink?: string;
}

const UserEdit = (props: { editObject: UserEditObject }) => {
  const { editObject } = props;
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [formObject] = Form.useForm();
  const [courseName, setCourseName] = useState([]);
  const [workType, setWorkType] = useState([]);
  const [teamName, setTeamName] = useState([]);
  const [studentName, setStudentName] = useState([]);
  const [editorState, setEditorState] = useState(EditorState.createEmpty());

  const flag = editObject.key !== null && editObject.key !== undefined;

  const selectDataSource = async () => {
    if (editObject.key !== null && editObject.key !== undefined) {
    } else {
      const dataCourseName = await request.post(
        '/api/teacher/Task/SelectCourse',
      );
      setCourseName(dataCourseName.data);

      const courseIds = await window.localStorage.getItem('courseId');

      const dataWorkType = await request.post(
        '/api/teacher/Task/JobType',
        qs.stringify({ id: courseIds }),
        { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } },
      );
      setWorkType(dataWorkType.data);

      const dataTeamName = await request.post(
        '/api/teacher/Task/SelectGroup',
        qs.stringify({ id: courseIds }),
      );
      setTeamName(dataTeamName.data);

      const teamId = window.localStorage.getItem('teamId');

      const dataStudentName = await request.post(
        '/api/teacher/Task/SelectStudents',
        qs.stringify({ id: courseIds, teamId: teamId }),
      );
      setStudentName(dataStudentName.data);
    }
  };

  const loadDataSource = async () => {
    const result: any = await request.get(
      '/api/teacher/Task/ViewJob/{id}' + editObject.key,
    );
    if (result.data.length != 0) {
      formObject.setFieldsValue({
        key: result.data.key,
        title: result.data.title,
        completeDate: moment(
          result.data.completeDate
            ? moment(result.data.completeDate).format('YYYY-MM-DD HH:mm')
            : '',
        ),
        courseName: result.data.courseName,
        appendsLink: result.data.appendsLink,
        workType: result.data.workType,
        teamName: result.data.teamName,
        studentName: result.data.studentName,
      });
    }
    if (flag) {
      const Draft = async () => {
        const contentBlock = await htmlToDraft(result.data.appendsLink || '');
        if (contentBlock) {
          const contentState = ContentState.createFromBlockArray(
            contentBlock.contentBlocks,
          );
          const editorState1 = EditorState.createWithContent(contentState);
          setEditorState(editorState1);
        }
      };
      Draft();
    } else {
      console.log(1);
    }
  };

  //页面初始化
  React.useEffect(() => {
    selectDataSource();
    setIsModalVisible(editObject.isModalVisible);
    if (editObject.key) {
      loadDataSource();
    }
  }, [editObject]);

  const onEditorStateChange = (editorState: any) => {
    setEditorState(editorState);
  };

  const modelOnCancel = () => {
    formObject.resetFields();
    setIsModalVisible(false);
  };

  const modelOnOk = async () => {
    if (flag) {
    } else {
      const studentId = await localStorage.getItem('studentId');
      const teamId = await localStorage.getItem('teamId');
      const data: any = await formObject.getFieldsValue();
      const values = {
        studentId: Array(studentId),
        completeDate: data.completeDate
          ? data.completeDate.format('YYYY-MM-DD HH:mm:ss')
          : '',
        courseId: data.courseName,
        teamInfoId: Array(teamId),
        title: data.title,
        workType: data.workType,
        appendsLink: data.appendsLink ? data.appendsLink.toString() : '',
      };
      //console.log(values);
      const result = await request.post('/api/teacher/Task/NewJob', values, {
        headers: { 'Content-Type': 'application/json' },
      });
      //console.log(result);
    }
    setIsModalVisible(false);
  };

  const formItemLayout = {
    labelCol: {
      span: 9,
    },
    wrapperCol: {
      span: 24,
    },
  };

  return (
    <>
      <Modal
        title={flag ? '查看作业' : '新增作业'}
        width="60%"
        visible={isModalVisible}
        onCancel={modelOnCancel}
        onOk={modelOnOk}
        maskClosable={false}
        destroyOnClose
        okText={flag}
        cancelText="取消"
      >
        <Form form={formObject} {...formItemLayout}>
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item label="作业主题" name="title">
                <Input placeholder="请输入..." />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item label="计划完成时间" name="completeDate">
                <DatePicker
                  style={{ width: '100%' }}
                  showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="选择课程" name="courseName">
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  onSelect={function (key: any) {
                    localStorage.setItem('courseId', key);
                  }}
                >
                  {(courseName || []).map((courseName: any) => {
                    return (
                      <option key={courseName.id} value={courseName.id}>
                        {courseName.course_name}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="作业类型" name="workType">
                <Select style={{ width: '100%' }} placeholder="请选择">
                  {(workType || []).map((workType: any) => {
                    return (
                      <option key={workType.workType} value={workType.workType}>
                        {workType.workTypeName}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item label="选择小组" name="teamName">
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  onSelect={function (key: any) {
                    localStorage.setItem('teamId', key);
                  }}
                >
                  {(teamName || []).map((teamName: any) => {
                    return (
                      <option key={teamName.id} value={teamName.id}>
                        {teamName.teamName}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={8}>
              <Form.Item label="选择学生" name="studentName">
                <Select
                  mode="tags"
                  style={{ width: '100%' }}
                  placeholder="请选择"
                  onSelect={function (key: any) {
                    localStorage.setItem('studentId', key);
                  }}
                >
                  {(studentName || []).map((studentName: any) => {
                    return (
                      <option
                        key={studentName.studentId}
                        value={studentName.studentId}
                      >
                        {studentName.studentName}
                      </option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24} style={{ width: '100%' }}>
            <Col span={10}>
              <Form.Item label="上传相关附件">
                <Upload {...props}>
                  <Button type="primary" icon={<UploadOutlined />}>
                    上传附件
                  </Button>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="appendLink">
            <Editor
              editorState={editorState}
              toolbarClassName="toolbarClassName"
              wrapperClassName="wrapperClassName"
              editorClassName="editorClassNam"
              placeholder="请输入作业内容..."
              onEditorStateChange={onEditorStateChange}
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export { UserEdit, UserEditObject };
